from Properties import Properties

# GLOBALS:

# load & parse properties file:
settingsFile = file("settings.properties", "r");
settings = Properties();
settings.load(settingsFile);

import sys
import time
import SendKeys
from watsup.launcher import *
from watsup.winGuiAuto import *
import FileDirUtils
import FineReader
import Djvu
from shutil import *

def mainListeningLoop():
    observedPath = settings.getProperty("finereader.input.folder")
    secondsIdle = int(settings.getProperty("listener.seconds.idle"))
    checkInterval = int(settings.getProperty("listener.check.interval"))
    
    currentDirs = FileDirUtils.getCurrentDirectories(observedPath)
    
    while True:
        time.sleep(checkInterval)
        updatedDirs = FileDirUtils.getCurrentDirectories(observedPath)
        newDirs = FileDirUtils.findAddedElements(currentDirs, updatedDirs)
        currentDirs = updatedDirs

        if len(newDirs) > 0:
            for newDir in newDirs:
                FileDirUtils.waitTillNoChangesDetected(newDir, secondsIdle, checkInterval)
                pdfs = FineReader.startProcessingForTree(newDir)
                for pdf in pdfs:
                    Djvu.process(newDir, pdf)
        
        if FineReader.findFineReaderMainWindow() == None:
            # closing FineReader main window terminates the script
            return

if __name__ == '__main__':
    
    #backup FineReader user config files as *_bkp: 
    frCfgFile = settings.getProperty('finereader.config.file')
    copyfile(frCfgFile, frCfgFile + '_bkp') # backup
    
    #override current user config by presets:
    copyfile(settings.getProperty('user.config.file'), frCfgFile)
    
    reload(sys)
    sys.setdefaultencoding('Cp1250')
    #sys.setdefaultencoding('utf-8') #TODO
    
    frForm = FineReader.launchFineReader()    
    
    mainListeningLoop()
    
    if FineReader.findFineReaderMainWindow() != None:
        terminateApp(frForm)
    
    #revert back to the original user config:
    copyfile(frCfgFile + '_bkp', frCfgFile)
    
    exit()
